package pl.maciejziarko.mshare.security;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import pl.maciejziarko.mshare.utils.Check;

/**
 * @author Maciej Ziarko
 */
@Component
public class ShiroSecurityService implements SecurityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShiroSecurityService.class);

    @Override
    public void login(AuthenticationToken authenticationToken) throws UnknownAccountException, AuthenticationException {
        Check.notNull(authenticationToken, "Authentication token cannot be null");

        Subject subject = SecurityUtils.getSubject();

        if (subject == null) {
            throw new AuthenticationException();
        }

        subject.login(authenticationToken);
    }

    @Override
    public void logout() throws AuthenticationException {
        Subject subject = SecurityUtils.getSubject();

        if (subject == null) {
            throw new AuthenticationException();
        }

        subject.logout();
    }

    @Override
    public String getUsername() throws AuthenticationException {
        Subject subject = SecurityUtils.getSubject();

        if (subject == null) {
            throw new AuthenticationException();
        }
        
        String username = (String) subject.getPrincipal();

        return username;
    }
}
